#include <iostream>
#include <stdfdsarewqfdsarewio.h>
#include <fstream>
#include <cstring>
#include "document.h"

using namespace std;

int Document::Open(char* fileName){
    fstream fs(fileName);
    if (!fs.good()){
        return -1;
    }
    string line;
    Row* p_row;
    while(getline(fs,line)){
        p_row = new Row(line);
        this->_rows.push_back(p_row);
    }
    this->FileName = new string();
    *(this->FileName) = fileName;
    return 0;
}


Document::Document(){

}


Document::~Document(){
    delete this->FileName;
    for(int i=0;i<this->_rows.size();i++){
        Row* p = this->_rows[i];
        delete p;
    }
}




Row* Document::GetRowByIndex(int index){
    if (IsEmpty() || (_rows.size()-1) < index){
        return NULL;
    }
    Row* row = _rows[index];
    return row;
}



bool Document::IsEmpty(){
    return _rows.size() == 0;
}


int Document::Len(){
    return _rows.size();
}


void Document::Insert(Position pos,char c){
    if (c=='\n'){
        this->InsertNewLine(pos);
        return;
    }
    if (pos.x == this->Len()){
        string str;
        str.push_back(c);
        Row* newRow = new Row(str);
        _rows.push_back(newRow);
    } else {
        Row* row  = _rows[pos.x];
        row->Insert(pos.y,c);
    }

}


void Document::Delete(Position at){
    int len = this->Len();
    if (at.x >= len){
        return;
    }
    
    if (at.y == _rows[at.x]->Length() && at.x < len -1){
        Row* nextRow = _rows[at.x+1];
        _rows.erase(_rows.begin()+at.x+1);
        Row* row = _rows[at.x];
        row->Append(nextRow);
    } else {
        Row* row = _rows[at.x];
        row->Delete(at.y);
    }
}


void Document::InsertNewLine(Position at){
    if (at.x > this->Len()){
        return;
    }

    if (at.x == this->Len()){
        _rows.push_back(new Row(""));
        return;
    }

    Row* newRow = this->_rows[at.x]->Split(at.y);
    this->_rows.insert(this->_rows.begin()+at.x+1,newRow);
}

int Document::Save(){
    if (this->FileName !=NULL){
        ofstream os(this->FileName->c_str(),std::ofstream::binary);
        for(int i=0;i<this->Len();i++){
           int contentLen = this->_rows[i]->Length();
           char* lineBuffer = new char[contentLen+1];
           strcpy(lineBuffer,this->_rows[i]->GetContent());
           lineBuffer[contentLen] = '\n';
           os.write(lineBuffer,contentLen+1);
           delete[] lineBuffer;
        }
        os.close();
        return 0;
    } else {
        return -1;
    }
    
}
